package tech.wetech.admin3.sys.service;
//package com.java.sdk.demo;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.kernel.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import tech.wetech.admin3.sys.model.AooUser;
import tech.wetech.admin3.sys.repository.AooUserRepository;
import tech.wetech.admin3.util.AooJwtUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;

import com.alipay.api.FileItem;

import java.util.Base64;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ScanLoginService {
  @Autowired
  private AooUserRepository userRepository;
  @Autowired
  private AooJwtUtil jwtUtil;
  private String appId = "wx2678dbd75e83b265";
  private String appSecret = "963022fded2cb6d5a7cbdb62a3722592";

  @Value("${alipay.easy.appId}")
  private String appIdAli;

  public String getAddress() throws UnsupportedEncodingException {
    String redirectUrl = URLEncoder.encode("https://www.szrdid.com/", "UTF-8");
    String url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redirectUrl
      + "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
    //    response.setContentType("image/png");
    //    QrCodeUtil.generate(url, 300, 300, "jpg", response.getOutputStream());
    return url;
  }

  public AooUser wxlogin(String code) throws Exception {
    if (StringUtils.isEmpty(code)) {
      throw new Exception("code不能为空");
    }
    // 验证state以防止CSRF攻击
    // 用code换取access_token
    String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId +
      "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code";
    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.getForObject(accessTokenUrl, String.class);
    JSONObject jsonObject = JSONObject.parseObject(response);
    String access_token = jsonObject.getString("access_token");
    String openid = jsonObject.getString("openid");
    log.info("扫码登录--用code获取---   {}", jsonObject);

    // 用access_token和openid获取用户信息
    String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
    String userInfoResponse = restTemplate.getForObject(userInfoUrl, String.class);
    JSONObject userInfoJson = JSONObject.parseObject(userInfoResponse);
    log.info("扫码登录--用access_token + openid获取---   {}", userInfoJson);

    String nickname = new String(userInfoJson.getString("nickname").getBytes("ISO-8859-1"), "UTF-8");
    log.info("nickname-----------------: {}", nickname);
    String headimgurl = userInfoJson.getString("headimgurl");
    String unionid = userInfoJson.getString("unionid");

    if (unionid == null) {
      throw new Exception(userInfoJson.toString());
    }

    // 保存/更新 用户信息
    AooUser user = saveUser(unionid, nickname, headimgurl);
    // token
    String token = jwtUtil.generateTokenWx(unionid);
    user.setToken(token);

    log.info("扫码登录返回---   {}", user);
    return user;
  }

  @Transactional
  public AooUser saveUser(String unionid, String nickname, String headimgurl) {
    // 检查数据库中是否已经有这个 unionid 字符串的Email
    AooUser user = userRepository.findByEmail(unionid);
    if (user == null) {
      // 如果没有，创建一个新的用户
      user = new AooUser();
      user.setEmail(unionid);
      user.setUsername(nickname);
      user.setAvatarUrl(headimgurl);
      user = userRepository.save(user);   // 保存并重新获取user对象
    } else {
      // 如果已经有这个 unionid，更新 sessionKey
      user.setUsername(nickname);
      user.setAvatarUrl(headimgurl);
      userRepository.save(user);
    }
    return user;
  }


}
